import cv2 as cv
import numpy as np
import pdb

videoFilename = r'D:\opencv\opencv\sources\samples\data\vtest.avi'

cap = cv.VideoCapture(videoFilename)
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200

while True:
    ret, frame = cap.read()
    if not ret: # 没读到当前帧，结束
        break

    fgmask =fgbg.apply(frame)
    _, fgmask = cv.threshold(fgmask, 30, 0xff, cv.THRESH_BINARY)

    bgImage = fgbg.getBackgroundImage()
    _, cnts, _ = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    # 创建白色幕布
    temp = np.ones(frame.shape, np.uint8) * 255
    # 画出轮廓：temp是白色幕布，contours是轮廓，-1表示全画，然后是颜色，厚度
    cv.drawContours(temp, cnts, -1, (0, 255, 0), 3)
    cv.imshow('bgImage', fgmask)
    cv.imshow('back', frame)
    cv.waitKey(30)